package com.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;


/**
 * @author 惊云
 * @date 2024/1/13 9:08
 */

@RestControllerAdvice
public class TraceResponseBodyAdvice  implements ResponseBodyAdvice {

    protected static Logger logger = LoggerFactory.getLogger(TraceResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {

        Class targetClass = returnType.getMethod().getDeclaringClass();
        logger.info("supports execute methodParameter={} targetClass={} class={}", returnType, targetClass, converterType);

        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        logger.info("beforeBodyWrite data={}", body);

        // response.addHeader("Pragma", "no-cache");

        // 这里计算签名值，并设置到请求头
        List<String> traceInfo = request.getHeaders().get("traceInfo");
        if(!CollectionUtils.isEmpty(traceInfo)){
            response.getHeaders().set("tranceInfo", traceInfo.get(0));
        }
        return body;
    }

}
